/**
 * 调试订单状态显示问题
 * 检查数据库中的实际订单状态分布
 */

const cloudbase = require('@cloudbase/node-sdk')

async function debugOrderStatus() {
  console.log('🔍 开始调试订单状态显示问题...')
  
  try {
    // 初始化云开发
    const app = cloudbase.init({
      env: process.env.TCB_ENV || 'your-env-id'
    })
    
    const db = app.database()
    
    console.log('\n📊 查询数据库中的订单状态分布...')
    
    // 获取所有订单
    const ordersResult = await db.collection('orders').get()
    const orders = ordersResult.data
    
    console.log(`总订单数: ${orders.length}`)
    
    if (orders.length === 0) {
      console.log('❌ 数据库中没有订单数据')
      return
    }
    
    // 统计状态分布
    const statusCount = {}
    orders.forEach(order => {
      const status = order.status || 'unknown'
      statusCount[status] = (statusCount[status] || 0) + 1
    })
    
    console.log('\n📈 实际状态分布:')
    Object.entries(statusCount).forEach(([status, count]) => {
      console.log(`  ${status}: ${count} 个订单`)
    })
    
    // 检查新标签应该显示的订单数量
    console.log('\n🏷️ 新标签应该显示的数量:')
    
    const newTabs = [
      { key: 'all', label: '全部' },
      { key: 'pending', label: '待处理', statuses: ['pending', 'rejected', 'reassigning'] },
      { key: 'confirmed', label: '已确认', statuses: ['confirmed'] },
      { key: 'waiting_team', label: '等待接单', statuses: ['waiting_team'] },
      { key: 'team_accepted', label: '已接单', statuses: ['team_accepted'] },
      { key: 'in_progress', label: '施工中', statuses: ['in_progress'] },
      { key: 'testing', label: '验收中', statuses: ['testing'] },
      { key: 'completed', label: '已完成', statuses: ['completed'] },
      { key: 'cancelled', label: '已取消', statuses: ['cancelled'] }
    ]
    
    newTabs.forEach(tab => {
      if (tab.key === 'all') {
        console.log(`  ${tab.label}: ${orders.length} 个订单`)
      } else {
        const count = orders.filter(order => 
          tab.statuses.includes(order.status)
        ).length
        console.log(`  ${tab.label}: ${count} 个订单`)
      }
    })
    
    // 检查是否有其他状态的订单
    const knownStatuses = [
      'pending', 'confirmed', 'surveying', 'designing', 'quoted',
      'waiting_team', 'team_accepted', 'team_preparing', 'team_on_site',
      'in_progress', 'paused', 'testing', 'completed', 'cancelled',
      'rejected', 'reassigning'
    ]
    
    const unknownStatuses = Object.keys(statusCount).filter(status => 
      !knownStatuses.includes(status)
    )
    
    if (unknownStatuses.length > 0) {
      console.log('\n⚠️ 发现未知状态:')
      unknownStatuses.forEach(status => {
        console.log(`  ${status}: ${statusCount[status]} 个订单`)
      })
    }
    
    // 检查是否有没有标签显示的状态
    const statusesWithoutTabs = Object.keys(statusCount).filter(status => 
      !['pending', 'confirmed', 'waiting_team', 'team_accepted', 'in_progress', 'testing', 'completed', 'cancelled', 'rejected', 'reassigning'].includes(status)
    )
    
    if (statusesWithoutTabs.length > 0) {
      console.log('\n🚨 这些状态没有对应的标签:')
      statusesWithoutTabs.forEach(status => {
        console.log(`  ${status}: ${statusCount[status]} 个订单`)
      })
      console.log('💡 建议: 为这些状态添加对应的标签或将它们归类到现有标签中')
    }
    
    console.log('\n✅ 调试完成')
    
  } catch (error) {
    console.error('❌ 调试过程中出错:', error)
    
    // 如果是环境问题，提供模拟数据测试
    console.log('\n🔄 使用模拟数据进行测试...')
    
    const mockOrders = [
      { id: '001', status: 'pending' },
      { id: '002', status: 'confirmed' },
      { id: '003', status: 'waiting_team' },
      { id: '004', status: 'team_accepted' },
      { id: '005', status: 'in_progress' },
      { id: '006', status: 'testing' },
      { id: '007', status: 'completed' },
      { id: '008', status: 'cancelled' }
    ]
    
    console.log('模拟数据状态分布:')
    const mockStatusCount = {}
    mockOrders.forEach(order => {
      mockStatusCount[order.status] = (mockStatusCount[order.status] || 0) + 1
    })
    
    Object.entries(mockStatusCount).forEach(([status, count]) => {
      console.log(`  ${status}: ${count} 个订单`)
    })
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  debugOrderStatus()
}

module.exports = { debugOrderStatus } 